import { login, logout,getInfo } from '@/api/index'
import { getToken, setToken, removeToken} from '@/utils/auth'
import router, { resetRouter } from '@/router'
import Cookies from 'js-cookie'

const state = {
  token: getToken(),
  nickname: '',
  roles: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NICKNAME: (state, nickname) => {
    state.nickname = nickname
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      login(userInfo).then(response => {
        const data = response.data
        if(response.code==1){
          commit('SET_TOKEN', data.token)
          Cookies.set('admin_id', data.info.id)
          setToken(data.token)
        }
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getUserInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo({token:state.token}).then(response => {
          const { data } = response
          if (!data) {
            reject('请先登录！')
          }
          const { nickname,permissions,bg_logo,logo } = data
          commit('SET_NICKNAME', nickname)

          //权限按钮组保存到本地缓存
          sessionStorage.setItem('ButtonPermissions',permissions)
          //左侧顶部logo
          Cookies.set('bg_logo',bg_logo)
          Cookies.set('logo',logo)

          resolve(data)

        }).catch(error => {
          reject(error)
        })
      })
  },





  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        removeToken()
        resetRouter()
        Cookies.remove('admin_id')
        dispatch('tagsView/delAllViews', null, { root: true })
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      //commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
